#include <fstream>
#include <iostream>
#include <string>
#include <filesystem>
#include <cstdint>

#include "ClassMate.hh"
#include "MyClass.hh"

int main(int argc, char **argv){
  ////////////check the command arguments///////////
  if(argc==1){
    std::cerr<<"ERROR, please give a data file"<<std::endl;
    return 1;
  }
  else if(argc!=2){
    std::cerr<<"ERROR, command reqires 1 argument.("
	     <<argc-1<<"given)"<<std::endl;
    return 1;
  }

  ////////////check the input file path/////////////
  std::filesystem::path inpath(*(argv+1));
  if(!std::filesystem::exists(inpath)){
    std::cerr<<"ERROR, file:  "
	     <<std::filesystem::absolute(inpath)
	     <<"  does not exist"<<std::endl;
    return 1;
  }

  /////////open input file 
  std::ifstream ifs(inpath.string().c_str());
  if(!ifs.is_open()) {
    std::cerr<<"Error opening the file!"<<std::endl;
    return 1;
  }

  ///////open output file
  std::filesystem::path outpath=std::filesystem::absolute(inpath).replace_filename("sortedstudentlist.txt");
  if(std::filesystem::exists(outpath)){
    std::filesystem::remove(outpath);
  }
  std::ofstream ofs(outpath.string().c_str());
  if(!ofs.is_open()) {
    std::cerr<<"Error opening the output file!"<<std::endl;
    return 1;
  }
  
  std::string aline;
 
  MyClass *myClass=nullptr;
  ClassMate *mateA = nullptr;
  
  int16_t mateNum = 0;
  while (std::getline(ifs, aline)){
    if(aline.size()<10){
      continue;
    }
    std::istringstream aline_iss(aline);
    uint64_t schoolID;
    std::string mateName;
    std::string groupName;
    std::string courseHour;
    std::string status;
    uint16_t genderINT;
    
    aline_iss>> schoolID>> mateName >> groupName >> courseHour >> status >> genderINT;

    bool isGirl= false;
    if(genderINT==1){
      isGirl = true;
    }
    ClassMate *aMate = new ClassMate(mateName, schoolID, isGirl, aline);
    //aMate->printInfo();

    mateNum= mateNum +1;
    if(mateNum==1){
      mateA = aMate;
      continue;
    } else if(mateNum==2){
      myClass = new MyClass(mateA, aMate);
      continue;
    }

    myClass->append(aMate); 
    
  }
  if(myClass==nullptr){
    return 1;
  }
    
  myClass->printClassMates();

  ClassMate *winnerMate = myClass->findLeastNameMate();

  std::cout<< "winnerMate=========================="<<std::endl;
  winnerMate->printInfo();
  

  
  
  ClassMate *aMate=myClass->m_headPtr;
  while(aMate!=nullptr){
    ofs<<aMate->m_meta<<std::endl;
    aMate=aMate->m_nextClassMate;
  }
 
  
  delete myClass;
  
  return 0;
}
